<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
          <el-form-item label="流程编号" prop="serialNumber">
            <el-input v-model="queryParams.serialNumber" placeholder="请输入流程编号" size="small" clearable style="width: 200px"/>
          </el-form-item>
          <el-form-item label="流程名称" prop="projectName">
            <el-input v-model="queryParams.projectName" placeholder="请输入流程名称" size="small" clearable style="width: 200px"/>
          </el-form-item>
          <el-form-item label="流程状态" prop="statusCode">
            <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
            </el-select>
          </el-form-item>
          <el-form-item label="发起时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"  v-hasPermi="['saveWorkflowRecord']"  icon="el-icon-plus" size="mini" @click="handleWorkflowModel">发起流程</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="queryMyWorkflowRecordPageResList" :columns="columns"></right-toolbar>
        </el-row>
        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" style="width: 100%"  @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column label="流程编号" align="left" prop="serialNumber" width="250" />
          <el-table-column label="流程名称" align="left" prop="projectName"/>
          <el-table-column label="发起时间" align="center" prop="createTime"  width="250" />
          <el-table-column label="流程状态" align="center" prop="statusName" width="200" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="当前节点" align="left" prop="taskName" >
            <template slot-scope="scope">
              {{scope.row.taskName}} <el-tag type="info" size="mini" v-if="scope.row.taskName">{{scope.row.taskId}}</el-tag>
            </template>
          </el-table-column>-->

          <el-table-column label="耗时" align="center" prop="durationTimeString" width="250"/>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" v-hasPermi="['submitWorkflowRecord']" v-if="scope.row.statusCode === 'WORKFLOW_TOBE_SUBMITTED'" type="text" icon="el-icon-finished" @click="submitWorkflowRecord(scope.row)">提交</el-button>
              <el-button size="mini"  v-if="scope.row.statusCode !== 'WORKFLOW_TOBE_SUBMITTED'" type="text" icon="el-icon-view" @click="handleWorkflowRecordDetails(scope.row)">详情</el-button>

              <el-dropdown v-if="scope.row.statusCode === 'WORKFLOW_TOBE_SUBMITTED'
               || scope.row.statusCode === 'WORKFLOW_RECORD_PROGRESS'"  v-hasPermi="['updateWorkflowRecord','deleteWorkflowRecord','cancelWorkflowApply']"  @command="(command) => handleCommand(command, scope.row)">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多操作
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-hasPermi="['updateWorkflowRecord']" v-if="scope.row.statusCode === 'WORKFLOW_TOBE_SUBMITTED'" command="updateWorkflowRecord" icon="el-icon-edit">修改</el-dropdown-item>

                  <el-dropdown-item v-hasPermi="['deleteWorkflowRecord']" v-if="scope.row.statusCode === 'WORKFLOW_TOBE_SUBMITTED'" command="deleteWorkflowRecord" icon="el-icon-delete">删除</el-dropdown-item>

                  <el-dropdown-item v-hasPermi="['cancelWorkflowApply']" v-if="scope.row.statusCode === 'WORKFLOW_RECORD_PROGRESS'" command="cancelWorkflowApply" icon="el-icon-circle-close">取消申请</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>

        </el-table>
        <pagination v-show="total>0"  :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="queryMyWorkflowRecordPageResList"/>
      </el-col>
    </el-row>

    <!-- 发起流程模型弹窗选择 -->
    <el-dialog :title="workflowModelTitle" :visible.sync="workflowModelOpen" width="800px" append-to-body>
      <el-row :gutter="20">
        <el-col>
          <el-form :model="queryWorkflowModelParams" ref="queryWorkflowModelForm" :inline="true" label-width="80px">
            <el-form-item label="流程名称" prop="projectName">
              <el-input v-model="queryWorkflowModelParams.projectName" placeholder="请输入流程名称" size="small" clearable style="width: 200px"/>
            </el-form-item>
            <el-form-item label="备注说明" prop="remark">
              <el-input v-model="queryWorkflowModelParams.remark" placeholder="请输入备注说明" size="small" clearable style="width: 200px"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleWorkflowModelQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetWorkflowModelQuery('queryWorkflowModelForm')">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :stripe="true" v-loading="loadingWorkflowModel" :data="workflowModelDataList" style="width: 100%">
            <el-table-column label="流程名称" align="left" prop="projectName" width="250" />
            <el-table-column label="备注" align="left" prop="remark"/>
            <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom' width="200" />
            <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleSaveWorkflow(scope.row)">发起流程</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="workflowModelTotal>0"  :total="workflowModelTotal" :page.sync="queryWorkflowModelParams.page" :limit.sync="queryWorkflowModelParams.rows" @pagination="queryNormalSelectWorkflowProjectPageResList"/>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 发起工作流弹窗 -->
    <el-dialog :title="workflowWriteTitle" center :visible.sync="workflowWriteOpen" append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane :label="workflowFormLabel" name="workflowWrite" style="height:550px;overflow-y:auto;overflow-x:auto;">

          <WorkflowFormAdd
            v-if="projectConfig.projectId&&workflowWriteType==='addWorkflow'"
            :key="projectConfig.projectId+new Date()"
            :project-config="projectConfig"
            @submit="saveWorkflowRecord"
          />

          <WorkflowFormEdit
            v-if="projectUpdateConfig.projectId&&workflowWriteType==='editWorkflow'"
            :key="projectUpdateConfig.projectId"
            :project-config="projectUpdateConfig"
            @submit="updateWorkflowRecord"
          />

        </el-tab-pane>
        <el-tab-pane label="流程图形" name="workflowChart" style="height:550px;overflow-y:auto;overflow-x:auto;">
          <div style="text-align: center; height: 100%;">
            <img :src="workflowWritePreviewImage"   class="image-item" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>


    <!-- 工作流详情 -->
    <el-dialog :title="workflowRecordDetailsTitle" center :visible.sync="workflowRecordDetailsOpen" width="800px"  append-to-body>
      <workflowRecordDetails
        v-if="workflowRecordDetailsRecordId"
        :key="workflowRecordDetailsRecordId"
        :record-id="workflowRecordDetailsRecordId"
        :project-id="workflowRecordDetailsProjectId"
      />
    </el-dialog>

  </div>
</template>

<script>
  import {queryMyWorkflowRecordPageResList, queryWorkflowRecordReadImage, saveWorkflowRecord,updateWorkflowRecord,
    submitWorkflowRecord,deleteWorkflowRecordByRecordId,cancelWorkflowApplyByRecordId} from '@/api/workflow/workflowRecord'
  import {queryNormalSelectWorkflowProjectPageResList,queryWorkflowProcessReadImage} from '@/api/workflow/workflowProject'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  import WorkflowFormAdd from './workflowFormAdd'
  import WorkflowFormEdit from './workflowFormEdit'
  import workflowRecordDetails from './view/workflowRecordDetails.vue'
  //默认查询参数
  let defaultQueryParams = {
    projectName: undefined,
    startTime: undefined,
    endTime: undefined,
    serialNumber: undefined,
    statusCode: "",
    page: 1,
    rows: 10
  }

  //工作流模型
  let workflowModelQueryParams = {
    projectName: undefined,
    remark: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: 'myWorkflowAdmin',
    components: {
      WorkflowFormAdd,
      WorkflowFormEdit,
      workflowRecordDetails
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        //内容集合
        dataList: [],
        // 日期范围
        dateRange: [],
        //流程状态
        statusOptions: [],
        //实例流程图片
        lookDialogVisible: false,
        //流程图片标题
        previewTitle:"",
        //流程图片图片
        previewImage: "",
        // 查询参数
        queryParams: { ...defaultQueryParams },
        // 工作流模型查询参数
        queryWorkflowModelParams: { ...workflowModelQueryParams },
        //工作流模型选择弹窗标题
        workflowModelTitle:"",
        //工作流模型选择弹窗是否打开
        workflowModelOpen:false,
        // 工作流模型遮罩层
        loadingWorkflowModel: true,
        // 工作流模型总条数
        workflowModelTotal: 0,
        //工作流模型内容集合
        workflowModelDataList: [],

        //发起工作流默认定位
        activeName: 'workflowWrite',
        //发起工作流配置
        projectConfig: {
          projectId: '',
          showBtns: true
        },
        //发起工作流里面的流程图
        workflowWritePreviewImage:"",
        //发起流程弹窗标题
        workflowWriteTitle:"",
        //发起工作流类型，是修改还是新增
        workflowWriteType:"addWorkflow",
        //发起流程初始tab 名称
        workflowFormLabel:"发起流程",
        //发起工作流弹窗
        workflowWriteOpen:false,
        //修改弹窗传参ID
        updateWorkflowRecordId:"",

        //发起工作流配置
        projectUpdateConfig: {
          projectId: ''
        },
        //工作流详情弹窗标题
        workflowRecordDetailsTitle:"",
        //工作流详情弹窗打开
        workflowRecordDetailsOpen:false,
        //工作流详情弹窗打开
        workflowRecordDetailsRecordId:"",
        //工作流项目ID
        workflowRecordDetailsProjectId:"",
        //列信息
        columns: []
      }
    },
    created() {
      this.initDict();
      this.queryMyWorkflowRecordPageResList()
    },
    methods: {
      //预览大图
      showPreviewImage(row) {
        const recordId={recordId:row.recordId}
        queryWorkflowRecordReadImage(recordId).then(res => {
          this.previewImage = res.data;
          this.previewTitle = row.projectName;
          this.lookDialogVisible = true;
        });
      },

      //获取数据字典
      initDict(){
        let dictArr = ["WORKFLOW_RECORD_STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['WORKFLOW_RECORD_STATUS']));
        });
      },

      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "updateWorkflowRecord":
            this.handleUpdateWorkflow(row);
            break;
          case "deleteWorkflowRecord":
            this.deleteWorkflowRecord(row);
            break;
          case "cancelWorkflowApply":
            this.cancelWorkflowApplyByRecordId(row);
            break;
          default:
            break;
        }
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.taskId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },

      //排序
      tableSortChange(column) {
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryMyWorkflowRecordPageResList()
      },
      /** 查询工作流我发起的记录列表 */
      queryMyWorkflowRecordPageResList() {
        this.loading = true
        queryMyWorkflowRecordPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
            this.dataList = res.data.records
            this.total = res.data.total
          }
        ).finally(() => {
          //关闭加载特效
          this.loading = false
        })
      },


      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = []
        this.resetForm(fromId)
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryMyWorkflowRecordPageResList()
      },

      /** 查询可选的工作流模型 */
      queryNormalSelectWorkflowProjectPageResList() {
        this.loadingWorkflowModel = true
        queryNormalSelectWorkflowProjectPageResList(this.queryWorkflowModelParams).then(res => {
            this.workflowModelDataList = res.data.records
            this.workflowModelTotal = res.data.total
          }
        ).finally(() => {
          //关闭加载特效
          this.loadingWorkflowModel = false
        })
      },
      /** 发起工作流弹窗按钮按钮操作 */
      handleWorkflowModel() {
        this.workflowModelOpen = true;
        this.workflowModelTitle = "发起流程";
        this.queryNormalSelectWorkflowProjectPageResList()
      },
      /**发起工作流保存弹窗*/
      handleSaveWorkflow(row){
        const projectId={projectId:row.projectId}
        queryWorkflowProcessReadImage(projectId).then(res => {
          let data = res.data;
          this.activeName = 'workflowWrite';
          this.workflowFormLabel = "发起流程";
          this.workflowWritePreviewImage =data?data:this.noImg;
          this.projectConfig.projectId = row.projectId
          this.workflowWriteOpen = true;
          this.workflowWriteType = "addWorkflow";
          this.workflowWriteTitle = row.projectName;
        });
      },
      /** 工作流模型重置按钮操作 */
      resetWorkflowModelQuery(fromId) {
        this.dateRange = []
        this.resetForm(fromId)
        this.handleWorkflowModelQuery()
      },
      /** 工作流模型搜索按钮操作 */
      handleWorkflowModelQuery() {
        this.queryWorkflowModelParams.page = 1
        this.queryNormalSelectWorkflowProjectPageResList()
      },

      //发起申请流程保存功能
      saveWorkflowRecord(data) {
        let saveReq = {
          'projectId': this.projectConfig.projectId,
          'originalData': data.formModel,
          'processData': data.labelFormModel
        }
        saveWorkflowRecord(saveReq).then(response => {
          this.$modal.msgSuccess(response.message)
          this.workflowModelOpen = false;
          this.workflowWriteOpen = false;
          this.queryMyWorkflowRecordPageResList()
        });
      },

      /**发起工作流保存弹窗*/
      handleUpdateWorkflow(row){
        const projectId={projectId:row.projectId}
        const recordId = row.recordId
        queryWorkflowProcessReadImage(projectId).then(res => {
          let data = res.data;
          this.activeName = 'workflowWrite';
          this.workflowFormLabel = "修改流程";
          this.workflowWritePreviewImage =data?data:this.noImg;
          this.projectUpdateConfig.projectId = recordId
          this.workflowWriteOpen = true;
          this.workflowWriteType = "editWorkflow";
          this.updateWorkflowRecordId = recordId;
          this.workflowWriteTitle = row.projectName+"  (流程编号:"+row.serialNumber+")";
        });
      },
      //发起申请流程修改功能
      updateWorkflowRecord(data) {
        let updateReq = {
          'recordId': this.updateWorkflowRecordId,
          'originalData': data.formModel,
          'processData': data.labelFormModel
        }
        updateWorkflowRecord(updateReq).then(response => {
          this.$modal.msgSuccess(response.message)
          this.workflowModelOpen = false;
          this.workflowWriteOpen = false;
          this.queryMyWorkflowRecordPageResList()
        });
      },

      /** 流程流转记录 */
      handleWorkflowRecordDetails(row){
        this.workflowRecordDetailsTitle = row.projectName+"  (流程编号:"+row.serialNumber+")";
        this.workflowRecordDetailsOpen = true;
        this.workflowRecordDetailsRecordId = row.recordId;
        this.workflowRecordDetailsProjectId = row.projectId;
      },
      /** 取消流程申请 */
      cancelWorkflowApplyByRecordId(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认取消所选流程申请?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const recordId={recordId:row.recordId}
          return cancelWorkflowApplyByRecordId(recordId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryMyWorkflowRecordPageResList();
        }).catch(function() {});
      },
      /** 提交流程 */
      submitWorkflowRecord(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认提交所选流程?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const recordId={recordId:row.recordId}
          return submitWorkflowRecord(recordId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryMyWorkflowRecordPageResList();
        }).catch(function() {});
      },
      /** 删除未提交的流程 */
      deleteWorkflowRecord(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选流程?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const recordId={recordId:row.recordId}
          return deleteWorkflowRecordByRecordId(recordId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryMyWorkflowRecordPageResList();
        }).catch(function() {});
      },


    }
  }
</script>
<style lang="scss">
  /* 图片原图大小自适应 等比缩放 */
  .image-item {
    max-width: 100%;
    max-height: 100%;
  }
</style>
